<script setup lang="tsx">
import { Form, FormSchema } from '@/components/Form'
import { useForm } from '@/hooks/web/useForm'
import { PropType, reactive, watch, ref, unref } from 'vue'
import { useValidator } from '@/hooks/web/useValidator'
import { useI18n } from '@/hooks/web/useI18n'
import { getMenuListApi, addMenu, updateMenu } from '@/api/menu'
import { ElTag } from 'element-plus'
import AddButtonPermission from './AddButtonPermission.vue'
import { BaseButton } from '@/components/Button'
import { cloneDeep } from 'lodash-es'

const { t } = useI18n()

const { required } = useValidator()

const props = defineProps({
  currentRow: {
    type: Object as PropType<any>,
    default: () => null
  }
})

const handleClose = async (tag: any) => {
  const formData = await getFormData()
  // 删除对应的权限
  setValues({
    permissionList: formData?.permissionList?.filter((v: any) => v.value !== tag.value)
  })
}

const showDrawer = ref(false)

const formSchema = reactive<FormSchema[]>([
  {
    field: 'type',
    label: '菜单类型',
    component: 'RadioButton',
    value: 0,
    colProps: {
      span: 24
    },
    componentProps: {
      options: [
        {
          label: '目录',
          value: 0
        },
        {
          label: '菜单',
          value: 1
        }
      ],
      on: {
        change: async (val: number) => {
          const formData = await getFormData()
          if (val === 1) {
            setSchema([
              {
                field: 'component',
                path: 'componentProps.disabled',
                value: false
              },
              {
                field: 'meta.alwaysShow',
                path: 'componentProps.disabled',
                value: true
              }
            ])
            setValues({
              component: unref(cacheComponent)
            })
            setValues({
              'meta.alwaysShow': '0'
            })
          } else {
            setSchema([
              {
                field: 'component',
                path: 'componentProps.disabled',
                value: true
              },
              {
                field: 'meta.alwaysShow',
                path: 'componentProps.disabled',
                value: false
              }
            ])

            if (formData.parentId === void 0) {
              setValues({
                component: '#'
              })
            } else {
              setValues({
                component: '##'
              })
            }
          }
        }
      }
    }
  },
  {
    field: 'parentId',
    label: '父级菜单',
    component: 'TreeSelect',
    componentProps: {
      nodeKey: 'id',
      props: {
        label: 'title',
        value: 'id',
        children: 'children'
      },
      highlightCurrent: true,
      expandOnClickNode: false,
      checkStrictly: true,
      checkOnClickNode: true,
      clearable: true,
      on: {
        change: async (val: number) => {
          const formData = await getFormData()
          if (val && formData.type === '0') {
            setValues({
              component: '##'
            })
          } else if (!val && formData.type === '0') {
            setValues({
              component: '#'
            })
          } else if (formData.type === '1') {
            setValues({
              component: unref(cacheComponent) ?? ''
            })
            setValues({
              meta: unref(cacheMeta)
            })
          }
        }
      }
    },
    optionApi: async () => {
      const res = await getMenuListApi('')
      return res.result || []
    }
  },
  {
    field: 'title',
    label: t('menu.menuName'),
    component: 'Input'
  },
  {
    field: 'component',
    label: '组件',
    component: 'Input',
    value: '#',
    componentProps: {
      disabled: true,
      placeholder: 'views/Authorization/Menu',
      on: {
        change: (val: string) => {
          cacheComponent.value = val
        }
      }
    }
  },
  {
    field: 'name',
    label: t('menu.name'),
    component: 'Input',
    componentProps: {
      placeholder: 'Menu'
    }
  },
  {
    field: 'icon',
    label: t('menu.icon'),
    component: 'IconPicker'
  },
  {
    field: 'path',
    label: t('menu.path'),
    component: 'Input',
    componentProps: {
      placeholder: 'menu'
    }
  },
  {
    field: 'meta.activeMenu',
    label: t('menu.activeMenu'),
    component: 'Input'
  },
  {
    field: 'status',
    label: t('menu.status'),
    component: 'Select',
    componentProps: {
      options: [
        {
          label: t('userDemo.disable'),
          value: '0'
        },
        {
          label: t('userDemo.enable'),
          value: '1'
        }
      ]
    },
    value: '1'
  },
  {
    field: 'permissionList',
    label: t('menu.permission'),
    component: 'CheckboxGroup',
    colProps: {
      span: 24
    },
    formItemProps: {
      slots: {
        default: (data: any) => (
          <>
            {data?.permissionList?.map((v) => {
              return (
                <ElTag class="mr-1" key={v.value} closable onClose={() => handleClose(v)}>
                  {v.label}
                </ElTag>
              )
            })}
            <BaseButton type="primary" size="small" onClick={() => (showDrawer.value = true)}>
              添加权限
            </BaseButton>
          </>
        )
      }
    }
  },
  {
    field: 'meta.hidden',
    label: t('menu.hidden'),
    component: 'Switch',
    componentProps: { 'active-value': '1', 'inactive-value': '0' },
    value: '0'
  },
  {
    field: 'meta.alwaysShow',
    label: t('menu.alwaysShow'),
    component: 'Switch',
    componentProps: { 'active-value': '1', 'inactive-value': '0' },
    value: '0'
  },
  {
    field: 'meta.noCache',
    label: t('menu.noCache'),
    componentProps: { 'active-value': '1', 'inactive-value': '0' },
    component: 'Switch',
    value: '0'
  },
  {
    field: 'meta.breadcrumb',
    label: t('menu.breadcrumb'),
    componentProps: { 'active-value': '1', 'inactive-value': '0' },
    component: 'Switch',
    value: '0'
  },
  {
    field: 'meta.affix',
    label: t('menu.affix'),
    componentProps: { 'active-value': '1', 'inactive-value': '0' },
    component: 'Switch',
    value: '0'
  },
  {
    field: 'meta.noTagsView',
    label: t('menu.noTagsView'),
    componentProps: { 'active-value': '1', 'inactive-value': '0' },
    component: 'Switch',
    value: '0'
  },
  {
    field: 'meta.canTo',
    label: t('menu.canTo'),
    componentProps: { 'active-value': '1', 'inactive-value': '0' },
    component: 'Switch',
    value: '0'
  }
])

const rules = reactive({
  component: [required()],
  path: [required()],
  name: [required()],
  'meta.title': [required()]
})

const { formRegister, formMethods } = useForm()
const { setValues, getFormData, getElFormExpose, setSchema } = formMethods

const submit = async () => {
  const elForm = await getElFormExpose()
  const valid = await elForm?.validate().catch((err) => {
    console.log(err)
  })
  if (valid) {
    const formData = await getFormData()
    const res = await addMenu(formData)
    if (!res.success) {
      return
    }
    console.log('submit', formData)
    return formData
  }
}

const updateData = async () => {
  const elForm = await getElFormExpose()
  const valid = await elForm?.validate().catch((err) => {
    console.log(err)
  })
  if (valid) {
    const formData = await getFormData()
    const res = await updateMenu(formData)
    if (!res.success) {
      return
    }
    console.log('updateMenu', formData)
    return formData
  }
}

const cacheComponent = ref('')
const cacheMeta = ref()
watch(
  () => props.currentRow,
  (value) => {
    if (!value) return
    console.log('currentRow', value)
    const currentRow = cloneDeep(value)
    cacheComponent.value = currentRow.type === 1 ? currentRow.component : ''
    cacheMeta.value = currentRow.type === 1 ? currentRow.meta.alwaysShow : '0'
    if (currentRow.parentId === 0) {
      setSchema([
        {
          field: 'component',
          path: 'componentProps.disabled',
          value: true
        }
      ])
    } else {
      setSchema([
        {
          field: 'component',
          path: 'componentProps.disabled',
          value: false
        }
      ])
    }
    if (currentRow.type == 1) {
      setSchema([
        {
          field: 'component',
          path: 'componentProps.disabled',
          value: false
        },
        {
          field: 'meta.alwaysShow',
          path: 'componentProps.disabled',
          value: true
        }
      ])
    } else {
      setSchema([
        {
          field: 'component',
          path: 'componentProps.disabled',
          value: true
        }
      ])
    }
    setValues(currentRow)
  },
  {
    deep: true,
    immediate: true
  }
)

defineExpose({
  updateData,
  submit
})

const confirm = async (data: any) => {
  const formData = await getFormData()
  setValues({
    permissionList: [...(formData?.permissionList || []), data]
  })
}
</script>

<template>
  <Form :rules="rules" @register="formRegister" :schema="formSchema" />
  <AddButtonPermission v-model="showDrawer" @confirm="confirm" />
</template>
